
<template>
    <div class="about">
        <NuxtLayout>
            <AboutMain :tree="tree" @clickNode="clickNode" />
        </NuxtLayout>
    </div>
</template>


<script setup lang='ts'>
import AboutMain from './c-comp/AboutMain.vue';
import { getDocsApi, editDocsApi, editStoreApi } from '@/service/api'
interface Tree {
    title: string
    children?: Tree[],
    [key: string]: any
}
const route = useRoute()

const { id, role } = route.params
const tree = ref<Tree[]>([])
let treeClone: Tree[] = [] // 用于同步更新后的tree
let total = 0

const getDocsFn = async () => {
    const { data } = await getDocsApi({ storeId: id })
    if (data.value?.code !== 200) return ElMessage.error(data.value?.msg)
    tree.value = data.value.data.map((doc: any) => {
        return {
            ...doc,
            label: doc.title,
            children: []
        }
    })
    treeClone = JSON.parse(JSON.stringify(unref(tree)))
    total = tree.value.map((item: Tree) => item.readNum).reduce((ac: number, cu: number) => ac + cu, 0)
}
getDocsFn()
provide('tree', tree)
const clickNode = (data: any) => {
    editDocsFn(data._id)
}

const editDocsFn = async (id: string) => {
    total += 1
    let readNum = ((treeClone.find((item: Tree) => item._id === id)) as Tree).readNum + 1
    const { data } = await editDocsApi({ id, readNum: readNum })
    if (data.value.code !== 201) return ElMessage.error(data.value.msg)
    treeClone[treeClone.findIndex((item: Tree) => item._id === id)] = data.value.data
}

const editStoreFn = async () => {
    const { data } = await editStoreApi({ id, readNum: total })
    if (data.value.code !== 201) return ElMessage.error(data.value.msg)
}

onBeforeRouteLeave((to, from, next) => {
    // 离开前更新阅读数
    editStoreFn()
    next()
})

onBeforeMount(() => {

})

</script>


<style scoped lang='scss'>
.about {}
</style>